
var m_CP_MainId=getUrlParam("mainId").substr(0,10);

var parameter = getRequest();
var username = parameter['userName'].substring(0,parameter['userName'].indexOf('?'));//参数名
// var m_CP_MainId=parameter['mainId'];
var m_cpdetail_id=0;

$(function(){

    console.log('m_CP_MainId='+m_CP_MainId);
    console.log(username);

    setStatusfhd(0)

    $("#billCode").textbox({disabled: true});
    $("#clientName").combobox("disable");

    $("#driver").textbox({disabled: true});
    $("#license_number").textbox({disabled: true});
    // $("#brokerage").textbox({disabled: true});
    $("#brokerage").combobox("disable");
    $("#remark").textbox({disabled: true});

    $("#savedB").show();
    $("#auditedB").hide();
    $("#invalidB").hide();

    setClient();
    // setbillmain();
    //
    // opencpbill();

    $.ajax({
        url: strLin + 'brokerage/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#brokerage').combobox({
                valueField: 'sid',
                textField: 'sname',
                data:cdata.data
            });
        }
    });

});




//设置页面
function setbillmain() {
    $("#billmain").datagrid({
        url: '',
        queryParams: {},
        striped: true,
        fit: true,
        showFooter: true,
        idField: 'iid',
        cache: false,
        rownumbers: true,
        rownumberWidth: 50,
        checkOnSelect: false,
        selectOnCheck: false,
        singleSelect: true,
        columns: [[
            {field: 'iid', title: '主键', hidden: true, width: 50},
            {field: 'order_code', title: '订单号', halign: 'center', align: 'center', width: 150},
            {field: 'goods_sid', title: '品名', halign: 'center', align: 'center', width: 250},
            {field: 'color', title: '颜色', halign: 'center', align: 'center', width: 150},
            // {field: 'color_code', title: '色号', halign: 'center', align: 'center', width: 130},
            // {field: 'color_code', title: '色块', halign: 'center', styler: colorStylerFormatter, align: 'center', width: 50},
            // {field: 'amount', title: '件数', halign: 'center', align: 'right', formatter: formatter, width: 80},
            {field: 'price', title: '单价', halign: 'center', align: 'right', width: 120},
            {field: 'kilo', title: '重量', halign: 'center', align: 'right',width: 150},
            {field: 'account_kilo', title: '调整/对账重量', halign: 'center', align: 'right',width: 150},

            {field: 'remark', title: '备注', halign: 'center', align: 'center',width: 200},
            // {field: 'state', checkbox: true, width: 50}

        ]],
        onClickRow:function (index, row) {

        },
    });
}

//合计
function computemain() {
    let rows = $("#billmain").edatagrid("getRows");
    let number = 0, qty = 0;
    for (let i = 0; i < rows.length; i++) {
        // number += parseFloat(rows[i].amount ? rows[i].amount : 0);
        qty += parseFloat(rows[i].kilo ? rows[i].kilo : 0);

    }
    $("#billmain").edatagrid('reloadFooter', [
        {
            order_code: '合计',
            // amount: number.toFixed(0),
            kilo: qty.toFixed(1),
        }
    ]);
}

//打开成品单据
function opencpbill() {
    $.ajax({
        url: strLin + 'billCp/selectByPrimaryKey/'+m_CP_MainId,
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
          console.log(cdata)
            $("#billCode").textbox('setValue',cdata.data.main.bill_code);
            $("#clientName").combobox('setValue', cdata.data.main.client_sid);

            $("#driver").textbox('setValue',cdata.data.main.driver);
            $("#license_number").textbox('setValue',cdata.data.main.license_number);
            $("#brokerage").combobox('setValue',cdata.data.main.brokerage);
            $("#remark").textbox('setValue',cdata.data.main.remark);

            $('#billmain').datagrid('loadData',cdata.data.details);

            computemain();
        }
    });
}

//修改单据
function updatebill() {
    $("#savedB").hide();
    $("#driver").textbox({disabled: false});
    $("#license_number").textbox({disabled: false});
    $("#brokerage").combobox("enable");
    $("#remark").textbox({disabled: false});

    setStatusfhd(1);

}

//修改保存单据
function savebill() {
    var billgrid=$('#billmain').datagrid('getRows');
    var m_driver = $("#driver").textbox('getValue');
    var m_license_number = $("#license_number").textbox('getValue');
    var m_brokerage = $("#brokerage").combobox('getText');
    var m_remark = $("#remark").textbox('getValue');

    let strSQL=  {
        // "details": billgrid,
        "details": [{"iid":billgrid[0].iid,"parent_id":m_CP_MainId}],
        "main": {
            "iid": m_CP_MainId,
            "driver": m_driver,
            "license_number": m_license_number,
            "brokerage": m_brokerage,
            "remark": m_remark
        }
    };
    console.log(strSQL);
    $.ajax({
        url: strLin + 'billCp/update',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(strSQL),
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
            console.log('修改成功data');
            $.messager.alert('提示','修改保存成功！');


            $("#savedB").show();
            $("#driver").textbox({disabled: true});
            $("#license_number").textbox({disabled: true});
            // $("#brokerage").textbox({disabled: true});
            $("#brokerage").combobox("disable");
            $("#remark").textbox({disabled: true});
            setStatusfhd(0);
        }
    });

}


//打印
function printbillfhd() {
console.log('打印')
if (m_CP_MainId>0){
    var strurl = strLinprint + "ReportServer?reportlet=printfhd.cpt&billID="+m_CP_MainId;
    // var strurl = "http://xdf206/zipperdye/ReportServer?reportlet=printfhd.cpt&billID="+m_CP_MainId;
   window.open(strurl);
}

}
//删除作废
function deletebillfhd() {
    $.messager.defaults = {ok: "确定", cancel: "取消", width: 300, closable: false};
    $.messager.confirm('确认', '您确认要作废当前单据吗？', function (r) {
        if (r) {

            $('#C').window('open');

        }
    });
}

//打开调整页面
function accountfhd() {
    var currentRow = $("#billmain").datagrid("getSelected");//获得选中行的信息
    if (currentRow==null || currentRow==undefined){
        console.log('退出函数');
        $.messager.alert('提示','请选择有效发货明细！');
        return;
    }
    var m_price =currentRow.price;
    var m_kilo  =currentRow.kilo;
    m_cpdetail_id=currentRow.iid;

    console.log(currentRow);

    $("#priceA").textbox('setValue', m_price);
    $("#accountqtyA").textbox('setValue',m_kilo);
    $('#A').window('open');
}

//设置按钮可用、不可用状态
function setStatusfhd(index) {
    let msg = {
        'tab0': ['保存单据'],
        'tab1': ['修改单据','打印发货单','作废单据'],
        'tab2': ['修改单据','打印发货单','作废单据','保存单据'],
        'tab3': ['修改单据','打印发货单','作废单据','保存单据','调整发货单'],
    };
    setTimeout(function () {
        $('#topfhd').find('a[class*="easyui-linkbutton"]').each(function (item, i) {
            let text = $(i).linkbutton('options').text;
            if (msg[`tab${index}`] == undefined) return false;
            if (msg[`tab${index}`].indexOf(text) > -1) {
                $(i).linkbutton('disable');
            } else {
                $(i).linkbutton('enable');
            }
        })
    }, 0);
}

//获取时间 getDate(0)
function getDate(param) {
    if (isNaN(param)) {
        param = 0;
    }
    var curDate = new Date();
    var newDate = new Date(curDate);
    newDate.setDate(curDate.getDate() + param);
    var year = newDate.getFullYear();
    var month = newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1;
    var date = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate();
    var separator = '-';
    return year + separator + month + separator + date;
}

//关闭当前标签页事件
function closeTab() {
    window.parent.closeTab();
}

//字段格式化
function formatter(v, r, i) {
    if (!isNaN(v) && v) {
        return v.toFixed(1);
    } else {
        return null;
    }
}


function SetClient() {
    let detailData=$('#billgrid').datagrid('getRows');
    if (detailData.length>0){
        $("#clientName").combobox("disable");  //不可用状态
        $('#setfhbill').linkbutton('enable');
    }else{
        $("#clientName").combobox("enable");   //恢复可用
        $('#setfhbill').linkbutton('disable');
    }
}


function setClient() {
    //设置客户下拉
    $.ajax({
        url: strLin + 'contact/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#clientName').combobox({
                valueField: 'sid',
                textField: 'sname',
                data:cdata.data
            });
            setbillmain();
            opencpbill();
        }
    });
}

/******************************************************************************/

/*设置时间格式*/
function add0(m) {
    return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

/*******************************************************************************/

//作废原因保存
function tovoidMemoSaveC() {
    let tovoidMemo=$("#tovoidMemo").textbox('getValue');
    let pass=$("#pass").textbox('getValue');
    if (tovoidMemo==null || tovoidMemo=='' ||tovoidMemo== undefined){
        $.messager.defaults = {ok: "确定", width: 300, closable: false};
        $.messager.alert('提示','作废原因必输，为空不允许保存！')
        return;
    }
    if (pass==null || pass=='' ||pass== undefined){
        $.messager.defaults = {ok: "确定", width: 300, closable: false};
        $.messager.alert('提示','密码必输，为空不允许保存！')
        return;
    }

    $.ajax({
        url: strLin + "dynamicQuery/querySqlString/select * from sys_user where username='"+ username + "' and password='" + pass + "'",
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            if (cdata.data.length>0){
                console.log('密码正确');

                let detailBill = $("#billmain").edatagrid("getRows");
                let etime = new Date();
                let m_date = format(etime);
                // let SQLstr={"main":{"iid":m_CP_MainId,"state":0,"nullify_remark":tovoidMemo,"nullify_time": m_date},"details":detailBill};
                let SQLstr={"main":{"iid":m_CP_MainId,"state":0,"nullify_remark":tovoidMemo,"nullify_time": m_date},
                    "details":[{"iid":detailBill[0].iid,"parent_id":m_CP_MainId}]};

                console.log(SQLstr);
                $.ajax({
                    url: strLin + 'billCp/update',
                    type: 'POST',
                    dataType: 'json',
                    data: JSON.stringify(SQLstr),
                    contentType: "application/json;charset=UTF-8",
                    success: function (data) {
                        console.log(data);
                        $.messager.alert('提示','删除作废完成！')
                        setStatusfhd(3)

                        $("#savedB").hide();
                        $("#auditedB").hide();
                        $("#invalidB").show();
                        $('#C').window('close');
                        $("#tovoidMemo").textbox("setValue", '');
                        $("#pass").textbox("setValue", '');
                    }
                });

            }else{
                $.messager.defaults = {ok: "确定", width: 300, closable: false};
                $.messager.alert('提示','密码错误！')
                $("#pass").textbox("setValue", '');
                return;
            }

        }
    });


}

//作废原因取消保存
function tovoidMemocancelC() {
    $('#C').window('close');
    $("#tovoidMemo").textbox("setValue", '');
    $("#pass").textbox("setValue", '');
}

//调整取消保存
function cancelaccountqtyA() {
    $('#A').window('close');
    $("#priceA").textbox("setValue", '');
    $("#accountqtyA").textbox("setValue", '');
}

//调整保存
function SaveaccountqtyA() {
    let m_price=$("#priceA").textbox('getValue');
    let m_kilo=$("#accountqtyA").textbox('getValue');
    // if (m_price==null || m_price=='' ||m_price== undefined){
    //     $.messager.defaults = {ok: "确定", width: 300, closable: false};
    //     $.messager.alert('提示','单价必输，为空不允许保存！')
    //     return;
    // }
    if (m_price==null || m_price=='' ||m_price== undefined){
        $.messager.defaults = {ok: "确定", width: 300, closable: false};
        $.messager.alert('提示','重量必输，为空不允许保存！')
        return;
    }

    let SQLstr={"main":{"iid":m_CP_MainId,"state":1},"details":[{"iid":m_cpdetail_id,"price":m_price,"account_kilo":m_kilo}]};
    console.log(SQLstr);

    $.ajax({
        url: strLin + 'billCp/update',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(SQLstr),
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
            console.log(data);
            $.messager.alert('提示','修改保存完成！')
            setStatusfhd(0)
            m_cpdetail_id=0;
            // $("#savedB").hide();
            // $("#auditedB").hide();
            // $("#invalidB").show();
            $('#A').window('close');
            $("#priceA").textbox("setValue", '');
            $("#accountqtyA").textbox("setValue", '');

            opencpbill();
        }
    });


}